import re
import json
import logging

from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.backends import ModelBackend
from django.contrib.auth.hashers import make_password
from django.core.paginator import PageNotAnInteger,Paginator
from django.db.models import Q
from django.http import HttpResponse,Http404
from django.shortcuts import render, redirect, render_to_response
from django.views.generic import View
from django.urls import reverse
# from django.core.urlresolvers import reverse
from apps.users.forms import RegisterForm, LoginForm, PasswordForgetForm, ModifyImageForm, PasswordResetForm, ModifyInfoForm
from apps.users.models import UserProfile, EmailVerifyRecord, Banner
from apps.users.utils import sendEmail
from apps.users.utils.checkFieldByReg import checkEmail
from apps.users.utils.mixin import LoginRequiredMiXin
from apps.courses.models import Course
from apps.organizations.models import Org, Teacher
from apps.users.utils.fileOper import delFileByPath
from apps.operations.models import UserCourse, UserMessage, UserFavorite


# def pageNotFound(request):
#     """
#     全局404处理函数
#     """
#     response = render_to_response("404.html", {})
#     response.status_code = 404
#     return response
# def pageError(request):
#     """
#     全局500处理函数
#     """
#     response = render_to_response("500.html", {})
#     response.status_code = 500
#     return response


class CustomBackend(ModelBackend):
    """
    重写django下ModelBackend类的authenticate方法,拓展邮箱,手机方式登录
    """
    def authenticate(self, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(username=username) | Q(email=username) | Q(mobilePhone=username))
            if user.check_password(password):
                return user
            return None
        except Exception as e:
            return None


class IndexView(View):
    """
    跳转到首页
    """
    def get(self, request):
        try:
            # 轮播图
            banners = Banner.objects.all().order_by("-index")
            # 课程
            coursesBanner = Course.objects.filter(isBanner=True)[:3]
            cousers = Course.objects.filter(isBanner=False)[:5]
            # 机构
            orgs = Org.objects.all()[:15]
            logger = logging.getLogger("info")
            logger.info("users-IndexView-get-%s", request.user.username)
            return render(request, "index.html", {"banners": banners, "cousers": cousers, "coursesBanners": coursesBanner, "orgs": orgs})
        except Exception as e:
            logger = logging.getLogger("debug")
            logger.debug("users-IndexView-get-%s %s", request.user.username, e)


class RegisterView(View):
    """
    注册：只能通过邮箱注册,手机方式未完成，注册成功后发送激活链接到指定邮箱
    """
    def get(self,request):
        return render(request,"userRegister.html",{"registerForm": RegisterForm()})
    def post(self,request):
        registerForm = RegisterForm(request.POST)
        if registerForm.is_valid():
            if UserProfile.objects.filter(email=registerForm.data["email"]):
                return render(request, "userRegister.html", {"msg": "该邮箱已经被注册过!", "registerForm": registerForm})
            userProfile = UserProfile()
            userProfile.username = registerForm.data["email"]
            userProfile.email = registerForm.data["email"]
            userProfile.password = make_password(registerForm.data["password"])
            userProfile.is_active = False
            # 邮件发送成功后再保存用户注册信息
            sendEmail.send(registerForm.data["email"],"register")
            userProfile.save()
            return render(request, "userLogin.html")
        return render(request, "userRegister.html", {"registerForm": registerForm})


class UserActiveView(View):
    """
    点击激活链接激活账户
    """
    def get(self, request, code):
        emailVerifyRecords = EmailVerifyRecord.objects.filter(code=code)
        if emailVerifyRecords:
            for emailVerifyRecord in emailVerifyRecords:
                user = UserProfile.objects.get(email=emailVerifyRecord.email)
                user.is_active = True
                # 账户激活后需删除邮箱信息
                user.save()
                emailVerifyRecord.delete()
            return render(request, "userLogin.html", {"msg": "激活成功!"})
        return render(request, "userActiveFail.html", {"msg": "激活失败！"})


class LoginView(View):
    """
    登录,没有激活的用户不允许登录
    """
    def get(self,request):
        try:
            return render(request, "userLogin.html")
        except Exception as e:
            logging.getLogger("custom").info("users.views.LoginView:get  {0}".format(e))
            raise Http404("该页面不存在")

    def post(self,request):
        loginForm = LoginForm(request.POST)
        if loginForm.is_valid():
				# 身份验证
                user = authenticate(username=loginForm.data["username"],password=loginForm.data["password"])
                if user is not None:
                    if user.is_active:
						# 登录
                        login(request, user)
                        return redirect(reverse("index"))
                    return render(request, "userLogin.html", {"msg": "您的账号还未激活,请到指定邮箱进行激活!"})
                else:
                    return render(request, "userLogin.html", {"msg": "用户名或者密码错误!"})
        else:
            return render(request, "userLogin.html", {"loginForm": loginForm})


class LogoutView(View):
    """
    用户退出登录
    """
    def get(self, requst):
        logout(requst)
        return render(requst, "userLogin.html")


class UserCenterInfoView(LoginRequiredMiXin, View):
    """
    用户个人中心--个人资料
    """
    def get(self,request):
        return render(request, "userCenterInfo.html", {})


class UserModifyImage(LoginRequiredMiXin, View):
    """
    个人中心--个人资料--修改头像
    """
    def post(self,request):
        upImageName = request.FILES["image"].name
        userImage = request.user.image
        if request.user.mobilePhone:
            imageName = request.user.mobilePhone
        else:
            imageName = request.user.email
        request.FILES["image"].name = re.sub(r'.*\.', imageName+".", upImageName)
        # 通过modifyImageForm实现UserProfile的保存
        modifyImageForm = ModifyImageForm(request.POST, request.FILES, instance=request.user)
        if modifyImageForm.is_valid():
            modifyImageForm.save()
            # 删除之前的头像信息
            if userImage != "HeadPortrait/default.png":
                delFileByPath(str(userImage))
            return HttpResponse("{\"status\":\"success\"}",content_type="application/json")
        return HttpResponse("{\"status\":\"fail\"}", content_type="application/json")


class UserModifyPassword(LoginRequiredMiXin, View):
    """
    用户个人中心--个人资料--修改密码
    """
    def post(self,request):
        passwordResetForm = PasswordResetForm(request.POST)
        password1 = request.POST.get("password", "")
        password2 = request.POST.get("nickName", "")
        if passwordResetForm.is_valid() and password1 == password2:
            user = request.user
            user.password = make_password(password1)
            user.save()
            return HttpResponse("{\"status\":\"success\"}", content_type="application/json")
        return HttpResponse("{\"status\":\"fail\"}", content_type="application/json")


class sendEmailCode(LoginRequiredMiXin,View):
    """
    用户个人中心--个人资料--修改邮箱
    """
    def post(self,request):
        email = request.POST.get("email", "")
        if checkEmail(email):
            if UserProfile.objects.filter(email=email):
                return HttpResponse("{\"status\":\"该邮箱已经被注册\"}", content_type="application/json")
            if EmailVerifyRecord.objects.filter(email=email, sendType="modifyEmail"):
                return HttpResponse("{\"status\":\"success\"}", content_type="application/json")
            sendEmail.send(email, "modifyEmail")
            return HttpResponse("{\"status\":\"success\"}", content_type="application/json")
        return HttpResponse("{\"status\":\"inputFail\"}", content_type="application/json")


class UserModifyEmail(LoginRequiredMiXin, View):
    """
    用户个人中心--个人资料--修改邮箱
    """
    def post(self,request):
        email = request.POST.get("email", "")
        code = request.POST.get("code", "")
        emailRecode = EmailVerifyRecord.objects.filter(code=code, email=email, sendType="modifyEmail")
        if emailRecode:
            user = request.user
            user.email = email
            user.save()
            emailRecode.delete()
            return HttpResponse("{\"status\":\"success\"}", content_type="application/json")
        return HttpResponse("{\"status\":\"codeFile\"}", content_type="application/json")


class UserModifyInfo(LoginRequiredMiXin, View):
    """
    用户个人中心--个人资料--保存用户信息
    """
    def post(self, request):
        modifyInfoForm = ModifyInfoForm(request.POST, instance=request.user)
        if modifyInfoForm.is_valid():
            modifyInfoForm.save()
            return HttpResponse("{\"status\":\"success\"}", content_type="application/json")
        return HttpResponse("{\"status\":\"fail\"}", content_type="application/json")


class PasswordForgetView(View):
    """
    1）点击"忘记密码"跳转到"邮箱验证""页面
    2）验证通过发送密码修改链接到指定邮箱
    """
    def get(self, request):
        return render(request, "userPasswordForget.html", {"passwordForgetForm": PasswordForgetForm()})

    def post(self, request):
        passwordForgetForm = PasswordForgetForm(request.POST)
        if passwordForgetForm.is_valid():
            if UserProfile.objects.filter(email=passwordForgetForm.data["email"]):
                sendEmail.send(passwordForgetForm.data["email"], "forget")
                return render(request, "userPasswordForget.html", {"msg": "重置密码链接已发送至指定邮箱,注意查收!"})
            return render(request, "userPasswordForget.html",
                          {"msg": "邮箱不存在!", "passwordForgetForm": passwordForgetForm})
        return render(request, "userPasswordForget.html", {"passwordForgetForm": passwordForgetForm})


class PasswordResetView(View):
    """
    3）点击指定邮箱内的密码修改链接跳转到“修改密码”页面
    """
    def get(self, request, code):
        emailVerifyRecords = EmailVerifyRecord.objects.filter(code=code)
        if emailVerifyRecords:
            for emailVerifyRecord in emailVerifyRecords:
                return render(request, "userPasswordReset.html", {"email": emailVerifyRecord.email})
        return render(request, "userResetFail.html")


class PasswordResetModifyView(View):
    """
    4）执行修改密码操作
    """
    def post(self, request):
        passwordResetForm = PasswordResetForm(request.POST)
        password1 = passwordResetForm.data["password"]
        password2 = passwordResetForm.data["nickName"]
        email = request.POST.get("email")
        if passwordResetForm.is_valid():
            if password1 == password2:
                user = UserProfile.objects.get(email=email)
                user.password = make_password(password2)
                user.save()
                EmailVerifyRecord.objects.filter(email=email, sendType="forget").delete()  # 重置成功后删除邮箱信息
                return render(request, "userLogin.html", {"msg": "密码修改成功!"})
            return render(request, "userPasswordReset.html", {"email": email, "msg": "两次输入的密码不一致"})
        return render(request, "userPasswordReset.html", {"email": email, "msg": "密码格式不正确"})


class UserCenterCourseView(LoginRequiredMiXin,View):
    """
    用户个人中心-我的课程
    """
    def get(self,request):
        userCourses = UserCourse.objects.filter(user=request.user)
        # 分页
        # try:
        #     page = request.GET.get("page",1)
        # except PageNotAnInteger:
        #     page = 1
        # p = Paginator(userCourses,5,request=request)
        # userCoursePage = p.page(page)
        return render(request,"userCenterCourse.html",{"userCourses": userCourses})


class UserCenterFavOrgView(LoginRequiredMiXin,View):
    """
    用户个人中心-我的收藏(机构)
    """
    def get(self,request):
        userFavorites = UserFavorite.objects.filter(user=request.user,favType=1)
        orgIds = [userFavorite.favId for userFavorite in userFavorites]
        orgs = Org.objects.filter(id__in=(orgIds))
        return render(request,"userCenterFavOrg.html",{"orgs":orgs})

class UserCenterFavTeavherView(LoginRequiredMiXin,View):
    """
    用户个人中心-我的收藏(教师)
    """
    def get(self,request):
        userFavorites = UserFavorite.objects.filter(user=request.user, favType=2)
        teacherIds = [userFavorite.favId for userFavorite in userFavorites]
        teachers = Teacher.objects.filter(id__in=(teacherIds))
        return render(request,"userCenterFavTeacher.html",{"teachers":teachers})

class UserCenterFavCourseView(LoginRequiredMiXin,View):
    """
    用户个人中心-我的收藏(课程)
    """
    def get(self,request):
        userFavorites = UserFavorite.objects.filter(user=request.user, favType=3)
        courseIds = [userFavorite.favId for userFavorite in userFavorites]
        courses = Course.objects.filter(id__in=(courseIds))
        return render(request,"userCenterFavCourse.html",{"courses":courses})


class UserCenterMessageView(LoginRequiredMiXin,View):
    """
    用户个人中心-我的消息
    """
    def get(self,request):
        userMessages = UserMessage.objects.filter(Q(user=request.user.id)|Q(user=0))
        # 设置为已读
        temps = UserMessage.objects.filter(user=request.user.id,hasRead=False)
        for temp in temps:
            temp.hasRead = True
            temp.save()
        # 分页
        # try:
        #     page = request.GET.get("page",1)
        # except PageNotAnInteger:
        #     page = 1
        # p = Paginator(userMessages,5,request=request)
        # userMessagePage = p.page(page)
        return render(request,"userCenterMessage.html",{"userMessages": userMessages})